package com.ant.backstage.controller;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import com.ant.backstage.config.shiro.JwtAuthenticatingFilter;
import com.ant.backstage.facade.dto.UserDTO;
import com.ant.backstage.facade.validation.UserConstant;
import com.ant.backstage.utils.RedisUtil;
import com.ant.backstage.utils.jwt.JwtUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
public class CommonMethod {

    private static Logger logger = LogManager.getLogger(CommonMethod.class);

    @Resource
    RedisUtil redisUtil;
    @Resource
    RedisTemplate redisTemplate;


    public UserDTO getUserInfoByToken(HttpServletRequest request) {
        String token = request.getHeader(UserConstant.AUTHORIZATION);
        // 从jwt字符串中解析出uid信息
        String uid = JwtUtil.getClaimByKey(token, "uid");
        boolean b = redisUtil.hasKey(uid + UserConstant.USER_TOKEN_SUFFIX);
        if (!b && JwtAuthenticatingFilter.shouldRefreshToken) {
            Subject subject = SecurityUtils.getSubject();
            UserDTO dto = (UserDTO) subject.getPrincipal();
            token = dto.getToken();
            uid = JwtUtil.getClaimByKey(token, "uid");
            JwtAuthenticatingFilter.shouldRefreshToken = false;
        }
        //redis 序列化方式  在特定情况下使用特定序列化方式
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        SimpleAuthenticationInfo info = (SimpleAuthenticationInfo) redisTemplate.opsForValue().get(uid + UserConstant.USER_TOKEN_SUFFIX);
        redisTemplate.setValueSerializer(new GenericFastJsonRedisSerializer());
        UserDTO userPo = (UserDTO) info.getPrincipals().getPrimaryPrincipal();
        return userPo;
    }
}
